var templates = {};
LoadMustacheTemplate('ratetable', templates);
LoadMustacheTemplate('sidebar', templates);

chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    var actionCommand = request.actionCommand;
    var options = {
    				request: request, 
    				sender: sender, 
    				response: sendResponse
    			}
    var func = window[actionCommand];
    
    if (typeof func == 'function') {
    	console.log('call ' + func);
    	func(options)
    }
  }
);

function GetBenchmarkRatesFromCache(options) {
	
	if(localStorage.benchmarkRates == undefined) {
		console.log('BenchmarkRates is undefined, call ReloadBenchmarkRates');
		ReloadBenchmarkRates(options);
		return;
	}
	console.log('Return cached benchmarkRates');
	options.response({"result": localStorage.benchmarkRates});
	
}

function ReloadBenchmarkRates(options) {
	$.ajax(
		{
			url: 'http://git.oschina.net/bhhzd/cfphelper/raw/master/data.json',
			type: 'get',
			data: options.params,
			context: options,
			async: false,
			beforeSend: function( xhr ) {
				xhr.setRequestHeader('X-Requested-With', {toString: function(){ return ''; }});
			}, 
			success: function(data) {
				var arr = $.parseJSON(data);
				arr[0].perday = 0;
				for(var i = 1; i < arr.length; i++ ) {
					var d = arr[i], d_1 = arr[i-1];
					arr[i].perday = (d.annualizedRate - d_1.annualizedRate) / (d.days - d_1.days);
				}
				localStorage.benchmarkRates = JSON.stringify(arr);
				options.response({"result": localStorage.benchmarkRates});
			}
		}
	);
}

function GetAutoLoading(options) {
	if(localStorage.AutoLoading == undefined) {
		localStorage.AutoLoading = false;
	}
	options.response({"result": localStorage.AutoLoading});
}

function StoreAutoLoading(options) {
	localStorage.AutoLoading = options.request.AutoLoading;
	options.response({"result": "AutoLoading" + localStorage.AutoLoading + " saved"});
}

function GetPlanPeriod(options) {
	if(localStorage.PlanPeriod == undefined || localStorage.PlanPeriod == 'undefined') {
		localStorage.PlanPeriod = 30;
	}
	options.response({"result": localStorage.PlanPeriod});
}

function StorePlanPeriod(options) {
	localStorage.PlanPeriod = options.request.PlanPeriod;
	options.response({"result": "PlanPeriod" + localStorage.PlanPeriod + "  saved"});
}

function LoadMustacheTemplate(template, templates) {
	var req = new XMLHttpRequest();
	var templateFile = 'template/' + template + '.html';
	req.open("GET", chrome.extension.getURL(templateFile), true);
	console.log('Loading template ' + templateFile + '...');
	req.onreadystatechange = function() {
    if (req.readyState == 4 && req.status == 200) {
        console.log(req.responseText);
        templates[template] = req.responseText;
    }
  };
  req.send(null);
}

function RenderRateTable(options) {
	
	if(templates[options.request.template] == undefined) {
		options.response({"result": ""});
		return;
	}
	
	var ratetable = JSON.parse(localStorage.benchmarkRates);
	$(ratetable).each(function(i){
			this.annualizedRatePercentForm = ToDecimal2(this.annualizedRate * 100) + '%';
	});
	
	var tb = Mustache.to_html(
		templates[options.request.template],
		{"rates": ratetable}
  );
  options.response({"result": tb});
  
}

function RenderSidebar(option) {
	if(templates[options.request.template] == undefined) {
		options.response({"result": ""});
		return;
	}
	options.response({"result": templates[options.request.template]});
}